package com.gandong8.trace.tool.service.impl;



import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.SendResult;
import com.aliyun.openservices.ons.api.bean.ProducerBean;

import com.gandong8.trace.tool.service.MqService;
import com.gandong8.trace.tool.util.JsonUtil;
import com.gandong8.trace.tool.util.TraceUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;

@Slf4j
@Service("onsService")
public class OnsService implements MqService {
    @Autowired(required = false) @Qualifier( "onsProducer" )
    //@Resource(name="onsProducer")
    ProducerBean producer;

    @Override
    public Boolean send(String topic, Object object) {
        return send(topic,  JsonUtil.toStr(object));
    }

    @Override
    public Boolean send(String topic, String msg) {
        return send(topic, null, null, msg);
    }

    @Override
    public Boolean send(String topic, String tag, String key, Object object) {
        return send(topic, tag, key, JsonUtil.toStr(object));
    }

    /**
     * 发送消息
     * @param topic 消息topic
     * @param tag 标签，对消息进行再归类
     * @param key 设置代表消息的业务关键属性，请尽可能全局唯一 方便您在无法正常收到消息情况下，可通过Console查询消息并补发
     * @param msg 消息内容
     * @return
     */
    @Override
    public Boolean send(String topic, String tag, String key, String msg) {
        log.info("开始发送消息：topic={},tag={},key={},msg={}" , topic, tag, key, msg);
        Message message = new Message(topic, tag, key, msg.getBytes(StandardCharsets.UTF_8));
        message.putUserProperties(TraceUtil.TRACE_TAG, TraceUtil.getTraceId());
        try {
            SendResult sendResult = producer.send(message);
            log.info("发送成功:"+sendResult.getMessageId());
        } catch (Exception e) {
            log.error("发送异常", e);
            //throw new GlobalException("发送消息异常");
        }
        return false;
    }
}
